import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LEGION
 * Date: 2023-11-09
 * Time: 16:13
 */

//导入jar包
public class Java231109 {
    public static void main(String[] args) throws SQLException {

//        不优雅也不安全  可能会导致sql注入攻击
//        Scanner scanner = new Scanner(System.in);
//        System.out.println("请输入要改的学号");
//        int id = scanner.nextInt();
//        System.out.println("请输入改后的姓名");
//        String name = scanner.next();

        //创建datasoures
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");


        //建立与数据库服务器之间的链接
        Connection connection = dataSource.getConnection();

        //构造sql吧sql发给服务器

        //String sql = "insert into student values(2,'张三')";
        //String sql = "delete from student where id = 1 ";
        //String sql = "update student set name = '张3' where id = 2 ";
        //String sql = "insert into student values("+id+",'"+name+"')";

        //增
        //String sql = "insert into student values(?,?)";
        //删
        //String sql = "delete from student where id = (?)";
        //改
       // String sql = "update student set name = (?) where id = (?)";

        //查
        String sql = "select * from student";

        PreparedStatement statement = connection.prepareStatement(sql);


//        statement.setString(1,name);
//        statement.setInt(2,id);
//       System.out.println("sq; = " + statement);

        //吧sql发给服务器s

        // update 增删改  返回值是个数，影响的行数
        //int n = statement.executeUpdate();

        ResultSet resultSet = statement.executeQuery();
       // 通过next方法，可以获取临时表的每一行数据，到最后一个，返回false 初始情况下光标指向第一行数据的前一个位置
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = " + id + ", name = " + name);
        }
      // System.out.println("n = " + n);

        //关闭链接,释放资源 释放顺序：后获取的资源先释放
//        statement.close();
//        connection.close();
        resultSet.close();
        statement.close();
        connection.close();

    }
}
